package org.secur.eave.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.github.shadowsocks.databinding.NodeItemBinding
import org.secur.eave.api.OnItemSelectedListener
import org.secur.eave.dao.StealthServer

class NodeAdapter(
        private val context: Context,
        private var list: List<StealthServer>,
        private val listener: OnItemSelectedListener
) : RecyclerView.Adapter<NodeAdapter.StealthServerViewHolder>() {
    
    private var selectedPosition: Int = -1
    
    inner class StealthServerViewHolder(val binding: NodeItemBinding) : RecyclerView.ViewHolder(binding.root)
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StealthServerViewHolder {
        val binding = NodeItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return StealthServerViewHolder(binding)
    }
    
    override fun getItemCount(): Int = list.size
    
    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewHolder(holder: StealthServerViewHolder, position: Int) {
        val node = list[position]
        
        holder.binding.apply {
            title.text = node.secureWaveRegion
            checkBox.isChecked = position == selectedPosition
            
            checkBox.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    // 更新选中位置
                    val previousPosition = selectedPosition
                    selectedPosition = position
                    notifyItemChanged(previousPosition) // 更新之前选中的项
                    notifyItemChanged(selectedPosition) // 更新当前选中的项
                    
                    // 调用接口方法
                    listener.onItemSelected(position, node)
                } else {
                    if (selectedPosition == position) {
                        selectedPosition = -1
                    }
                }
            }
        }
    }
}
